<template>
  <div class="app-container">
    <div style="margin-bottom: 50px">
      <el-card :style="{ height: contentHeight + 'px', overflow: 'auto' }">
        <el-steps
          style="max-width: 100%; transform: scale(0.6)"
          :active="active"
          finish-status="success"
          align-center
        >
          <el-step title="基础配置" />
          <el-step title="映射配置" />
          <el-step title="API配置" />
        </el-steps>
        <div v-if="active === 0" style="display: flex; justify-content: center">
          <el-form
            ref="baseConfigRef"
            style="max-width: 700px"
            :model="baseConfig"
            status-icon
            :rules="baseConfigRules"
            label-width="90px"
          >
            <el-form-item label="平台名称" prop="name">
              <el-input v-model="baseConfig.name" clearable placeholder="请输入平台名称" />
            </el-form-item>
            <el-form-item label="平台代码" prop="code">
              <el-input
                v-model="baseConfig.code"
                clearable
                placeholder="请输入平台代码"
                maxlength="16"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="平台地址" prop="host">
              <el-input v-model="baseConfig.host" clearable placeholder="请输入平台地址" />
            </el-form-item>
            <el-form-item label="请求头" prop="headers">
              <el-form :model="row" :rules="keyValueRules" style="width: 100%">
                <el-table :data="baseConfig.headers" border style="width: 100%">
                  <el-table-column type="index" width="50" />
                  <el-table-column prop="key" label="字段名">
                    <template #default="{ row }">
                      <el-form-item prop="key">
                        <el-input v-model="row.key" placeholder="请输入字段名" clearable />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="value" label="值">
                    <template #default="{ row }">
                      <el-form-item prop="value">
                        <el-input v-model="row.value" placeholder="请输入值" clearable />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" label="操作" min-width="30">
                    <template #default="scope">
                      <el-button
                        link
                        type="primary"
                        size="small"
                        @click.prevent="deleteHearderRow(scope.$index)"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>

              <el-button :icon="Plus" style="width: 100%" size="small" @click="addHearderRow">
                添加请求头
              </el-button>
            </el-form-item>
            <el-form-item v-if="flase" label="通用参数" prop="query">
              <el-form :model="row" :rules="keyValueRules" style="width: 100%">
                <el-table :data="baseConfig.query" border style="width: 100%">
                  <el-table-column type="index" width="50" />
                  <el-table-column prop="key" label="字段名">
                    <template #default="{ row }">
                      <el-form-item prop="key">
                        <el-input
                          v-model="row.key"
                          placeholder="请输入字段名"
                          clearable
                          @input="inputChange(row)"
                        />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="value" label="值">
                    <template #default="{ row }">
                      <el-form-item prop="value">
                        <el-input v-model="row.value" placeholder="" clearable />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" label="操作" min-width="30">
                    <template #default="scope">
                      <el-button
                        link
                        type="primary"
                        size="small"
                        @click.prevent="deleteQueryRow(scope.$index)"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>

              <el-button :icon="Plus" style="width: 100%" size="small" @click="addQueryRow">
                添加通用参数
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div v-show="active === 1">
          <Config ref="configRef" />
        </div>
        <div v-if="active === 2" class="flex">
          <el-tabs
            v-model="apiTab"
            tab-position="left"
            class="demo-tabs"
            style="width: 20%; height: 240px; line-height: 40px"
          >
            <el-tab-pane
              v-for="(api, index) in apiConfig"
              :key="index"
              :label="getNameCn(api.name)"
              :name="api.name"
            ></el-tab-pane>
          </el-tabs>

          <div v-for="(api, index) in apiConfig" :key="index">
            <div
              v-show="apiTab === api.name"
              style="width: 95%; margin-bottom: 40px; margin-left: 40px"
            >
              <el-form
                ref="apiConfigRef"
                :model="api"
                status-icon
                label-width="auto"
                :rules="apiConfigRules"
              >
                <el-form-item label="名称" prop="name">
                  <el-input :value="getNameCn(api.name)" disabled />
                </el-form-item>
                <el-form-item label="路由" prop="path">
                  <el-input v-model="api.path" clearable placeholder="请输入接口路由" />
                </el-form-item>
                <el-form-item label="请求方式" prop="method">
                  <el-select v-model="api.method" placeholder="请选择请求方式">
                    <el-option
                      v-for="method in methods"
                      :key="method.value"
                      :label="method.name"
                      :value="method.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="参数" prop="parameter">
                  <el-table :data="api.parameter" border style="width: 100%">
                    <el-table-column type="index" width="50" />
                    <el-table-column prop="key" label="字段名">
                      <template #default="{ row }">
                        <el-form ref="keyValueRulesRef" :model="row" :rules="keyValueRules">
                          <el-form-item prop="key">
                            <el-input
                              v-model="row.key"
                              placeholder="请输入字段名"
                              clearable
                              :disabled="row.disabled"
                            />
                          </el-form-item>
                        </el-form>
                      </template>
                    </el-table-column>
                    <el-table-column prop="value" label="值">
                      <template #default="{ row }">
                        <el-form ref="keyValueRulesRef" :model="row" :rules="keyValueRules">
                          <el-form-item prop="value">
                            <el-input
                              v-model="row.value"
                              placeholder="请输入值"
                              clearable
                              :disabled="row.disabled"
                            />
                          </el-form-item>
                        </el-form>
                      </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" min-width="50">
                      <template #default="scope">
                        <el-button
                          link
                          type="primary"
                          size="small"
                          @click.prevent="deleteAvaliablesRow(scope.$index, api)"
                        >
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-button
                    :icon="Plus"
                    style="width: 100%"
                    size="small"
                    @click="addAvaliablesRow(api)"
                  >
                    添加参数
                  </el-button>

                  <el-checkbox v-model="api.parameterInURL">参数应用到 Query</el-checkbox>
                </el-form-item>

                <el-form-item v-if="flase" label="回复内容" prop="extracts">
                  <el-table :data="api.extracts" border style="width: 100%">
                    <el-table-column type="index" width="50" />
                    <el-table-column prop="key" label="字段名">
                      <template #default="{ row }">
                        <el-form ref="keyValueRulesRef" :model="row" :rules="keyValueRules">
                          <el-form-item prop="key">
                            <el-input
                              v-model="row.key"
                              placeholder="请输入字段名"
                              clearable
                              @input="inputChange(row)"
                              @change="changeExtractsKey(api)"
                            />
                          </el-form-item>
                        </el-form>
                      </template>
                    </el-table-column>
                    <el-table-column prop="value" label="值">
                      <template #default="{ row }">
                        <el-input v-model="row.value" disabled />
                      </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" min-width="50">
                      <template #default="scope">
                        <el-button
                          link
                          type="primary"
                          size="small"
                          @click.prevent="deleteExtractsRow(scope.$index, api)"
                        >
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-button
                    :icon="Plus"
                    style="width: 100%"
                    size="small"
                    @click="addExtractsRow(api)"
                  >
                    添加回复内容
                  </el-button>
                </el-form-item>
              </el-form>
              <el-collapse style="width: 97%; margin-top: 20px; margin-left: 3%">
                <!-- <el-collapse-item title="用户配置" name="2"></el-collapse-item> -->
                <el-collapse-item name="3" title="请求构建脚本">
                  <div
                    v-if="apiTab == api.name && refresh"
                    class="script-editor"
                    style="margin-top: 20px"
                  >
                    <MonacoEditor
                      v-model="api.scripts[0]"
                      language="javascript"
                      @lintError="handleErrors"
                    />
                    <div style="display: flex; margin-top: 20px">
                      <el-button
                        type="primary"
                        style="margin-right: 10px"
                        @click="handleTestScript(api.scripts[0], api)"
                      >
                        测试
                      </el-button>
                      <el-input v-model="api.scriptParams" placeholder="请输入测试参数"></el-input>
                    </div>
                    <div class="test-result">测试结果: {{ JSON.stringify(api.scriptResult) }}</div>
                  </div>
                </el-collapse-item>
                <el-collapse-item title="解析结果脚本" name="1">
                  <div
                    v-if="apiTab == api.name && refresh"
                    class="script-editor"
                    style="margin-top: 20px"
                  >
                    <MonacoEditor
                      v-model="api.scripts[1]"
                      language="javascript"
                      @lintError="handleErrors"
                    />
                    <div style="display: flex; margin-top: 20px">
                      <el-button
                        type="primary"
                        style="margin-right: 10px"
                        @click="handleTestCode(api.scripts[1], api.testParam, api)"
                      >
                        测试
                      </el-button>
                      <el-input v-model="api.testParam" placeholder="请输入测试参数"></el-input>
                    </div>
                    <div class="test-result">测试结果: {{ JSON.stringify(api.testResult) }}</div>
                  </div>
                </el-collapse-item>
              </el-collapse>

              <el-row :gutter="18">
                <el-col :span="16">
                  <div class="test-content paramConfig">
                    <div class="title">用户配置</div>
                    <el-table :data="custom" border style="width: 100%">
                      <!-- <el-table-column type="index" width="50" /> -->
                      <el-table-column prop="label" label="字段名">
                        <template #default="{ row }">
                          <el-form ref="keyValueRulesRef" :model="row" :rules="keyValueRules">
                            <el-form-item prop="label">
                              <el-input v-model="row.label" placeholder="请输入字段名" clearable />
                            </el-form-item>
                          </el-form>
                        </template>
                      </el-table-column>
                      <el-table-column prop="key" label="字段代码">
                        <template #default="{ row }">
                          <el-form ref="keyValueRulesRef" :model="row" :rules="keyValueRules">
                            <el-form-item prop="key">
                              <el-input v-model="row.key" placeholder="请输入字段" clearable />
                            </el-form-item>
                          </el-form>
                        </template>
                      </el-table-column>
                      <el-table-column prop="type" label="类型">
                        <template #default="{ row }">
                          <el-select v-model="row.type" placeholder="请选择类型">
                            <el-option label="字符串(String)" value="string" />
                            <el-option label="数字(Number)" value="number" />
                            <el-option label="布尔(Boolean)" value="boolean" />
                            <el-option label="国家(Alpha-2)" value="Alpha-2" />
                            <el-option label="国家(Alpha-3)" value="Alpha-3" />
                          </el-select>
                        </template>
                      </el-table-column>
                      <el-table-column prop="semantic" label="标识">
                        <template #default="{ row }">
                          <el-select v-model="row.semantic" placeholder="请选择标识" clearable>
                            <el-option label="产品" value="product" />
                            <el-option label="国家" value="country" />
                          </el-select>
                        </template>
                      </el-table-column>
                      <el-table-column prop="required" label="是否必填">
                        <template #default="{ row }">
                          <el-switch v-model="row.required" />
                        </template>
                      </el-table-column>
                      <el-table-column prop="description" label="提示文字">
                        <template #default="{ row }">
                          <el-input
                            v-model="row.description"
                            placeholder="请输入提示文字"
                            clearable
                          />
                        </template>
                      </el-table-column>
                      <el-table-column fixed="right" label="操作" width="60">
                        <template #default="scope">
                          <el-button
                            link
                            type="primary"
                            size="small"
                            @click.prevent="deleteCustomRow(scope.$index)"
                          >
                            删除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <el-button :icon="Plus" style="width: 100%" size="small" @click="addCustomRow">
                      添加参数
                    </el-button>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="test-content">
                    <div class="title">测试</div>
                    <div
                      v-if="!custom.length || !custom[0].key"
                      style="
                        width: 100%;
                        padding: 20px 0;
                        font-size: 14px;
                        color: #999;
                        text-align: center;
                      "
                    >
                      请先配置参数
                    </div>
                    <el-form
                      v-if="refreshTestForm"
                      ref="testFormRef"
                      :rules="testFormRules"
                      style="max-width: 500px"
                      status-icon
                      label-width="auto"
                      :model="testForm"
                    >
                      <el-form-item
                        v-for="(item, index) in custom"
                        :key="index"
                        :label="item.key && item.label && item.type ? item.label : ''"
                        :prop="item.key"
                      >
                        <el-switch
                          v-if="item.type === 'boolean' && item.key"
                          v-model="testForm[item.key]"
                        />
                        <el-input
                          v-if="item.type === 'string' && item.key"
                          v-model="testForm[item.key]"
                          clearable
                          :placeholder="item.description"
                        />
                        <el-input-number
                          v-if="item.type === 'number' && item.key"
                          v-model="testForm[item.key]"
                          clearable
                          :placeholder="item.description"
                          style="width: 200px"
                        />
                        <el-select
                          v-if="item.type === 'Alpha-2' && item.key"
                          v-model="testForm[item.key]"
                          placeholder="请选择"
                          :clearable="true"
                          filterable
                        >
                          <el-option
                            v-for="item in countriesList"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code"
                          >
                            <span
                              class="flag-icon"
                              :class="`flag-icon-${item.code.toLowerCase()}`"
                            ></span>
                            <span style="margin-left: 5px">{{ item.name }}</span>
                          </el-option>
                        </el-select>
                        <el-select
                          v-if="item.type === 'Alpha-3' && item.key"
                          v-model="testForm[item.key]"
                          placeholder="请选择"
                          :clearable="true"
                          filterable
                        >
                          <el-option
                            v-for="item in countriesList3"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code"
                          >
                            <span
                              class="flag-icon"
                              :class="`flag-icon-${item.code2.toLowerCase()}`"
                            ></span>
                            <span style="margin-left: 5px">{{ item.name }}</span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item v-if="custom.length && custom[0].key && false">
                        <div style="display: flex; justify-content: flex-end; width: 100%">
                          <el-button type="primary" @click="handleTest()">生成链接</el-button>
                          <!-- 这里需要调接口 -->
                        </div>
                      </el-form-item>
                    </el-form>

                    <div v-if="testRes && false" class="test-res">
                      <div class="test-item">
                        <el-tooltip
                          class="box-item"
                          effect="dark"
                          :content="testRes.number.url"
                          placement="top-start"
                        >
                          <div class="test-item-title">
                            获取手机号： {{ testRes.number.url || "--" }}
                          </div>
                        </el-tooltip>

                        <el-button
                          size="small"
                          type="primary"
                          link
                          style="margin-left: 10px"
                          @click="copyCode(testRes.number.url)"
                        >
                          复制
                        </el-button>
                        <el-button
                          size="small"
                          type="primary"
                          link
                          @click="openLink(testRes.number.url)"
                        >
                          打开
                        </el-button>
                      </div>
                      <div class="test-item">
                        <el-tooltip
                          class="box-item"
                          effect="dark"
                          :content="testRes.code.url"
                          placement="top-start"
                        >
                          <div class="test-item-title">
                            获取验证码： {{ testRes.code.url || "--" }}
                          </div>
                        </el-tooltip>

                        <el-button
                          size="small"
                          type="primary"
                          link
                          style="margin-left: 10px"
                          @click="copyCode(testRes.code.url)"
                        >
                          复制
                        </el-button>
                        <el-button
                          size="small"
                          type="primary"
                          link
                          @click="openLink(testRes.code.url)"
                        >
                          打开
                        </el-button>
                      </div>
                      <div class="test-item">
                        <el-tooltip
                          class="box-item"
                          effect="dark"
                          :content="testRes.free.url"
                          placement="top-start"
                        >
                          <div class="test-item-title">
                            释放手机号： {{ testRes.free.url || "--" }}
                          </div>
                        </el-tooltip>
                        <el-button
                          size="small"
                          type="primary"
                          link
                          style="margin-left: 10px"
                          @click="copyCode(testRes.free.url)"
                        >
                          复制
                        </el-button>
                        <el-button
                          size="small"
                          type="primary"
                          link
                          @click="openLink(testRes.free.url)"
                        >
                          打开
                        </el-button>
                      </div>
                      <div class="test-item">
                        <el-tooltip
                          class="box-item"
                          effect="dark"
                          :content="testRes.black.url"
                          placement="top-start"
                        >
                          <div class="test-item-title">
                            拉黑手机号： {{ testRes.black.url || "--" }}
                          </div>
                        </el-tooltip>
                        <el-button
                          size="small"
                          type="primary"
                          link
                          style="margin-left: 10px"
                          @click="copyCode(testRes.black.url)"
                        >
                          复制
                        </el-button>
                        <el-button
                          size="small"
                          type="primary"
                          link
                          @click="openLink(testRes.black.url)"
                        >
                          打开
                        </el-button>
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>
              <div>
                <div class="get-template-btn">
                  <el-button type="primary" style="margin-right: 10px" @click="handleTest(api)">
                    预览
                  </el-button>
                  <el-input
                    v-model="testItem[api.name].json"
                    :autosize="{ minRows: 2, maxRows: 20 }"
                    type="textarea"
                    disabled
                  />
                </div>
                <div
                  v-if="testItem[api.name].json"
                  style="display: flex; justify-content: flex-end; width: 100%; margin-top: 10px"
                >
                  <el-button type="primary" link @click="copyText(testItem[api.name].command)">
                    复制 command
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <div class="footer">
      <el-button v-if="active >= 1" @click="router.back()">取消</el-button>
      <el-button @click="cancelConfig">{{ active > 0 ? "上一步" : "取消" }}</el-button>
      <el-button type="primary" @click="saveConfig">{{ active < 2 ? "下一步" : "保存" }}</el-button>
    </div>
  </div>
</template>

<script setup>
import Config from "./config.vue";
import { useRouter } from "vue-router";
// import { addApi, previewApi, getListApi, adminPreview } from "@/api/platformConfig/index.api";
import { addApi, getListApi, adminPreview } from "@/api/platformConfig/index.api";
import { Plus } from "@element-plus/icons-vue";
import MonacoEditor from "@/components/MonacoEditor/MonacoEditor.vue";
import useCountries from "@/hooks/useCountries";
import { copyText } from "@/utils";
import CryptoJS from "crypto-js";
const { countriesList, countriesList3 } = useCountries();

const handleErrors = (e) => {
  console.log(e);
};

const active = ref(0);
const router = useRouter();
// const tabName = ref("baseConfig");
const apiTab = ref("number");
const refresh = ref(false);

const baseConfigRef = ref(null);
const keyValueRulesRef = ref(null);
const apiConfigRef = ref(null);

const baseConfigRules = ref({
  name: [{ required: true, message: "请输入平台名称", trigger: "blur" }],
  code: [
    { required: true, message: "请输入平台代码", trigger: "blur" },
    { min: 3, max: 16, message: "长度在 3 到 16 个字符", trigger: "blur" },
    { pattern: /^[a-zA-Z0-9]+$/, message: "只支持英文、数字", trigger: "blur" },
  ],
  // host: [{ required: false, message: '请输入平台地址', trigger: 'change' }, { type: 'url', message: '请输入正确的网址', trigger: 'change' }],
});

const keyValueRules = ref({
  key: [{ required: false, message: "请输入字段名", trigger: "blur" }],
  value: [{ required: false, message: "请输入字段值", trigger: "blur" }],
  label: [{ required: false, message: "请输入字段描述", trigger: "blur" }],
});

const apiConfigRules = ref({
  url: [{ required: false, message: "请输入接口路由", trigger: "blur" }],
  method: [{ required: false, message: "请选择请求方式", trigger: "change" }],
});

const baseConfig = ref({
  name: "",
  code: "",
  host: "http://",
  headers: [{ key: "Content-type", value: "application/json" }],
  query: [],
});

const apiConfig = ref([
  {
    name: "number",
    method: "GET",
    paramType: "object",
    path: "",
    parameterInURL: false,
    parameter: [],
    testParam: "",
    testResult: "",
    scripts: [codeTemplate, codeTemplate],
    extracts: [{ key: "result", value: "{{result}}", inject: false }],
  },
  {
    name: "code",
    method: "GET",
    paramType: "object",
    path: "",
    parameterInURL: false,
    parameter: [],
    testParam: "",
    testResult: "",
    scripts: [codeTemplate, codeTemplate],
    extracts: [{ key: "result", value: "{{result}}", inject: false }],
  },
  {
    name: "free",
    method: "GET",
    paramType: "object",
    path: "",
    parameterInURL: false,
    parameter: [],
    testParam: "",
    testResult: "",
    scripts: [codeTemplate, codeTemplate],
    extracts: [{ key: "result", value: "{{result}}", inject: false }],
  },
  {
    name: "black",
    method: "GET",
    paramType: "object",
    path: "",
    parameterInURL: false,
    parameter: [],
    testParam: "",
    testResult: "",
    scripts: [codeTemplate, codeTemplate],
    extracts: [{ key: "result", value: "{{result}}", inject: false }],
  },
  {
    name: "success",
    method: "GET",
    paramType: "object",
    path: "",
    parameterInURL: false,
    parameter: [],
    testParam: "",
    testResult: "",
    scripts: [codeTemplate, codeTemplate],
    extracts: [{ key: "result", value: "{{result}}", inject: false }],
  },
  {
    name: "balance",
    method: "GET",
    paramType: "object",
    path: "",
    parameterInURL: false,
    parameter: [],
    testParam: "",
    testResult: "",
    scripts: [codeTemplate, codeTemplate],
    extracts: [{ key: "result", value: "{{result}}", inject: false }],
  },
]);

// const handleChangeParamType = (api, paramType) => {
//   if (paramType == "string") api.parameter = "{{body}}";
//   else api.parameter = [];
// };

watch(active, (val) => {
  if (val === 1) {
    nextTick(() => {
      refresh.value = true;
    });
  }
});

watch(
  baseConfig.value.query,
  (val) => {
    const bases = val.map((item) => {
      return {
        key: item.key,
        value: item.value,
        disabled: true,
      };
    });

    const uniqueArr = (arr, field) => {
      return arr.filter((item, index, self) => {
        return self.findIndex((t) => t[field] === item[field]) === index;
      });
    };

    apiConfig.value.map((api) => {
      if (Array.isArray(api.parameter)) {
        api.parameter = uniqueArr(
          [...bases, ...api.parameter.filter((item) => !item.disabled)],
          "key"
        );
      } else if (typeof api.parameter == "string") {
        // 什么也不处理
      } else {
        api.parameter = bases;
      }
    });

    return;
    // apiConfig.value.map((api) => {
    //   api.parameter = [];
    // });
    // val.map((item) => {
    //   apiConfig.value.map((api) => {
    //     api.parameter.push({
    //       key: item.key,
    //       value: item.value,
    //       disabled: true,
    //     });
    //   });
    // });
  },
  { deep: true }
);

const handleTestCode = (code, param, api) => {
  try {
    const fun = eval(code);
    let result = null;
    if (fun.length > 1) result = fun(testForm.value, param);
    else result = fun(param);
    api.testResult = result;
  } catch (error) {
    api.testResult = error.message;
    ElMessage.error("脚本语法有误！");
  }
};

const handleTestScript = (code, api) => {
  try {
    const fun = eval(code);
    api.scriptResult = fun(api.scriptParams);
  } catch (error) {
    api.scriptResult = error.message;
    ElMessage.error("脚本语法有误！");
  }
};

// const fillParams = () => {
//   const params = apiConfig.value[0].extracts;
//   const originals = apiConfig.value.map((item) => {
//     return item.parameter;
//   });

//   for (let i = 1; i < apiConfig.value.length; i++) {
//     const parameter = apiConfig.value[i].parameter;
//   }
// };

// export enum EResult {
//     ESuccess = 0, // 请求成功，返回数据
//     ENormal = 1, // 请求正常，但无数据
//     EFailed = 2  // 请求失败，严重错误
// }

// const codemirrorRef = ref(null);
const changeExtractsKey = () => {};

const codeTemplate = `(ctx) => {

}`;

const getNameCn = (name) => {
  return (
    {
      number: "获取号码",
      code: "获取验证码",
      free: "释放号码",
      black: "拉黑号码",
      success: "事件上报",
      balance: "获取余额",
    }[name] || name
  );
};

const methods = ref([
  { value: "get", name: "GET" },
  { value: "post", name: "POST" },
]);

const custom = ref([
  { key: "", type: "string", name: "", required: true, description: "请输入", semantic: "" },
]);

const testForm = ref({});
const testFormRules = ref({});
watch(
  custom,
  (fields) => {
    testForm.value = {};
    testFormRules.value = {};
    fields.map((field) => {
      if (!field.key || !field.type) return;
      if (field.type === "string") testForm.value[field.key] = "";
      else if (field.type === "number") testForm.value[field.key] = 0;
      else if (field.type === "boolean") testForm.value[field.key] = false;
      else testForm.value[field.key] = "";
      testFormRules.value[field.key] = [
        {
          required: field.required,
          type: ["string", "number", "boolean"].includes(field.type) ? field.type : "string",
          message: field.description || "请输入",
          trigger: "blur",
        },
      ];
    });
  },
  { deep: true }
);

/**
 * 请求头
 */
const addHearderRow = () => {
  baseConfig.value.headers.push({ key: "", value: "" });
};
const deleteHearderRow = (index) => {
  baseConfig.value.headers.splice(index, 1);
};

/**
 * 通用参数
 */
const addQueryRow = () => {
  baseConfig.value.query.push({ key: "", value: "" });
};
const deleteQueryRow = (index) => {
  baseConfig.value.query.splice(index, 1);
};

// const testRequest = async (api) => {
//   let formEls = [baseConfigRef.value];
//   const isArr = (e) => {
//     if (Array.isArray(e)) return (formEls = [...formEls, ...e]);
//   };
//   isArr(keyValueRulesRef.value);
//   isArr(apiConfigRef.value);

//   let count = 0;
//   let errorFlag = false;

//   formEls.forEach(async (formEl) => {
//     await formEl.validate((valid, fields) => {
//       if (!valid) {
//         if (errorFlag) return;
//         ElMessage.error("请检查输入项");
//         errorFlag = true;
//       }

//       count++;
//       if (count === formEls.length) {
//         previewApi({ layout: formatConfig() }).then((res) => {
//           console.log(res);
//         });
//       }
//     });
//   });
// };

/**
 * API参数配置
 */
const deleteAvaliablesRow = (index, api) => {
  api.parameter.splice(index, 1);
};
const addAvaliablesRow = (api) => {
  api.parameter.push({ key: "", value: "" });
};

// 导出数据
const deleteExtractsRow = (index, api) => {
  api.extracts.splice(index, 1);
};
const addExtractsRow = (api) => {
  api.extracts.push({ key: "", inject: false });
};

/**
 * 用户参数
 */
const deleteCustomRow = (index) => {
  custom.value.splice(index, 1);
};
const addCustomRow = () => {
  custom.value.push({
    key: "",
    type: "string",
    name: "",
    required: false,
    description: "请输入",
    semantic: "",
  });
};

const testRes = ref(null);
const testItem = ref({
  number: {},
  code: {},
  black: {},
  free: {},
  success: {},
  balance: {},
});
const testFormRef = ref(null);
const refreshTestForm = ref(true);
const handleTest = (api) => {
  const params = formatConfig();
  params.custom.forEach((item) => {
    item.value = testForm.value[item.key];
  });

  // if(api) {
  //   adminPreview({layout: params}).then(res => {
  //     testItem.value[api.name] = res[api.name]
  //     testItem.value[api.name].json = JSON.stringify(res[api.name], null, 4);
  //   })
  //   return
  // }

  refreshTestForm.value = false;
  nextTick(() => {
    refreshTestForm.value = true;
  });
  setTimeout(async () => {
    await testFormRef.value[0].validate((valid, fields) => {
      if (valid) {
        const layoutParams = JSON.parse(JSON.stringify(params));
        const variables = layoutParams.custom.map((item) => {
          const res = {
            key: item.key,
            value: item.value,
          };
          item.value = "";
          return res;
        });
        adminPreview({ layout: layoutParams, variables, route: api.name }).then((res) => {
          testItem.value[api.name] = res;
          testItem.value[api.name].json = JSON.stringify(res, null, 4);
        });
      } else {
        console.log("error submit!", fields);
      }
    });
  }, 100);
};

/**
 * footer
 */
const saveConfig = async () => {
  if (active.value === 0) {
    await baseConfigRef.value.validate(async (valid) => {
      if (!valid) {
        return ElMessage.error("请检查输入项");
      }
      return active.value++;
    });
    return;
  }

  if (active.value < 2) {
    return active.value++;
  }
  addApi({ layout: formatConfig() }).then(() => {
    router.back();
    ElMessage({
      message: "保存成功",
      type: "success",
    });
  });
};
const cancelConfig = () => {
  if (active.value > 0) {
    active.value--;
  } else {
    router.back();
  }
};

const configRef = ref(null);
const formatConfig = () => {
  const getArrToObj = (arr) => {
    const obj = {};
    arr.map((item) => {
      obj[item.key] = item.value;
    });
    return obj;
  };

  const getRoutes = (apiConfig) => {
    return apiConfig.map((api) => {
      return {
        name: api.name,
        path: api.path || "",
        method: api.method,
        parameter:
          typeof api.parameter == "string"
            ? api.parameter
            : api.parameter.map((item) => {
                return {
                  key: item.key,
                  value: item.value,
                  disabled: item.disabled || false,
                };
              }),
        parameterInURL: api.parameterInURL || false,
        scripts: [
          CryptoJS.MD5(codeTemplate).toString(CryptoJS.enc.Hex) ===
          CryptoJS.MD5(api.scripts[0]).toString(CryptoJS.enc.Hex)
            ? ""
            : api.scripts[0],
          CryptoJS.MD5(codeTemplate).toString(CryptoJS.enc.Hex) ===
          CryptoJS.MD5(api.scripts[1]).toString(CryptoJS.enc.Hex)
            ? ""
            : api.scripts[1],
        ],
        // extracts: api.extracts,
      };
    });
  };

  const { countries, products, iso, case_ } = configRef.value.getData();

  console.log(case_, "case_");

  const layout = {
    name: baseConfig.value.name,
    code: baseConfig.value.code,
    host: baseConfig.value.host,
    headers: getArrToObj(baseConfig.value.headers),
    query: baseConfig.value.query,
    routes: getRoutes(apiConfig.value),
    custom: JSON.parse(JSON.stringify(custom.value)),
    testing: testForm.value,
    countries,
    products,
    iso,
    case: case_,
  };
  return layout;
};

const objToArr = (obj) => {
  const arr = [];
  for (let key in obj) {
    arr.push({ key, value: obj[key] });
  }
  return arr;
};

const showScript = ref(false);
const getConfig = async (code) => {
  const { count, rows } = await getListApi({
    page: 1,
    size: 1,
    code,
  });

  if (count === 0) return;
  if (rows.length === 0) return;
  const { layout } = rows[0];

  configRef.value.setData(layout);

  baseConfig.value = {
    name: layout.name,
    code: layout.code,
    host: layout.host,
    headers: objToArr(layout.headers),
    query: layout.query,
    scripts: layout.scripts,
  };

  for (let i = 0; i < layout.routes.length; i++) {
    const routerItem = layout.routes[i];
    apiConfig.value[i] = routerItem;
    apiConfig.value[i].scripts = routerItem.scripts || [codeTemplate, codeTemplate];
    if (typeof routerItem.parameter == "string") {
      apiConfig.value[i].paramType = "string";
    } else {
      apiConfig.value[i].paramType = "object";
    }

    // 处理接口返回空数组
    if (!apiConfig.value[i].scripts.length) {
      apiConfig.value[i].scripts = [codeTemplate, codeTemplate];
    }
    // 处理接口返回 scripts 元素为非字符串
    for (let i = 0; i < apiConfig.value[i].scripts.length; i++) {
      apiConfig.value[i].scripts[i] = apiConfig.value[i].scripts[i] || codeTemplate;
    }

    if (typeof apiConfig.value[i].scripts == "string") {
      apiConfig.value[i].scripts = ["", apiConfig.value[i].scripts];
    }
  }

  custom.value = Array.isArray(layout.custom)
    ? layout.custom.map((item) => {
        if (item.semantic === "internal") item.semantic = "";
        return item;
      })
    : [];
  showScript.value = true;
  nextTick(() => {
    if (layout.testing) {
      testForm.value = layout.testing;
    }
  });
};

const copyCode = (text) => {
  document.oncopy = (e) => {
    e.clipboardData.setData("text", text);
    e.preventDefault();
    document.oncopy = null;
  };
  document.execCommand("Copy");
  ElMessage.success("复制成功");
};

const openLink = (url) => {
  window.open(url);
};

const contentHeight = ref(0);
onMounted(() => {
  nextTick(() => {
    const navbar = document.getElementsByClassName("navbar");
    const scrollbar = document.getElementsByClassName("tags-container");
    const windowHeight = document.documentElement.clientHeight;
    const topHeight = navbar[0].clientHeight + scrollbar[0].clientHeight;
    contentHeight.value = windowHeight - topHeight - 90;
  });

  if (!router.currentRoute.value.query.code) return (showScript.value = true);
  getConfig(router.currentRoute.value.query.code);
});

const inputChange = (e) => {
  e.value = `{{${e.key}}}`;
};
</script>

<style scoped lang="scss">
.config-content {
  margin-top: 20px;
}

.test-res {
  padding: 20px;
  margin-top: 50px;
  color: #ccc;
  border-top: 1px solid #ccc;

  .test-item {
    display: flex;
    margin-bottom: 10px;

    .test-item-title {
      max-width: 300px;
      /* 设置宽度 */
      overflow: hidden;
      /* 不换行 */
      text-overflow: ellipsis;
      /* 隐藏超出宽度的文本 */
      white-space: nowrap;
      /* 添加省略号 */
    }
  }
}

.footer {
  position: fixed;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  height: 50px;
  padding-right: 20px;
  background-color: var(--el-bg-color-overlay);
}

.script-editor {
  margin-left: 20px;
}

.test-result {
  width: 100%;
  padding: 20px;
  margin-top: 20px;
  // border: #ccc 1px solid;
  background-color: #cccccc30;
  border-radius: 8px;
}

.test-content {
  width: 100%;
  padding: 20px 0;
  margin-top: 40px;
  border-top: 1px solid #cccccc60;

  .title {
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: 600;
  }
}

.test-txt-content {
  width: 100%;
  height: 40px;
  padding-left: 20px;
  line-height: 40px;
  background-color: #cccccc20;
  border: 1px solid #cccccc60;
}

.get-template-btn {
  display: flex;
}

:deep(.el-form-item__error) {
  position: static !important;
}

:deep(.paramConfig .el-form-item--default) {
  margin-bottom: 0 !important;
}

:deep(.paramConfig .el-form-item) {
  margin-bottom: 0 !important;
}
</style>
